import time
import unittest

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from unittest import TestCase

class TestWebsite(TestCase):
    def setUp(self):
        """在每个测试方法之前运行"""
        self.driver = webdriver.Edge()
        self.driver.implicitly_wait(10)
        self.base_url = 'http://127.0.0.1:5000'

    def tearDown(self):
        """在每个测试方法之后运行"""
        if hasattr(self, 'driver'):
            self.driver.quit()

    def _register_user(self, username, email, password, password2):
        """注册用户的辅助方法"""
        self.driver.get(f'{self.base_url}/register')

        username_input = self.driver.find_element(By.ID, 'username')
        username_input.send_keys(username)

        email_input = self.driver.find_element(By.ID, 'email')
        email_input.send_keys(email)

        password_input = self.driver.find_element(By.ID, 'password')
        password_input.send_keys(password)
        time.sleep(1)

        password2_input = self.driver.find_element(By.ID, 'password2')
        password2_input.send_keys(password2)
        time.sleep(1)

        submit_button = self.driver.find_element(By.CLASS_NAME, 'btn')
        submit_button.click()

    def test_register_success(self):
        """测试注册成功的情况"""
        self._register_user('testuser123', 'testuser123@test.com', '123456', '123456')
        time.sleep(2)
        # 验证是否跳转到登录页面
        try:
            WebDriverWait(self.driver, 5).until(
                EC.url_to_be(f'{self.base_url}/login')
            )
            self.assertEqual(self.driver.current_url, f'{self.base_url}/login')
        except TimeoutException:
            self.fail("注册失败，未跳转到登录页面")

    def test_register_failure_duplicate_username(self):
        """测试注册失败 - 用户名已存在"""
        # 尝试使用相同用户名再次注册
        self._register_user('testuser123', 'another@test.com', '123456', '123456')

        # 验证是否停留在注册页面
        self.assertEqual(self.driver.current_url, f'{self.base_url}/register')
        time.sleep(2)
    def test_register_failure_password_mismatch(self):
        """测试注册失败 - 两次密码不匹配"""
        self._register_user('newuser123', 'newuser123@test.com', '123456', '1234567')

        # 验证是否停留在注册页面
        self.assertEqual(self.driver.current_url, f'{self.base_url}/register')
        time.sleep(2)
if __name__ == '__main__':
    unittest.main()